package com.xgf.demo.util;


import com.xgf.demo.authorization.config.Constants;
import org.apache.log4j.MDC;

import javax.servlet.http.HttpServletRequest;

public class UserUtil {
    private UserUtil userUtil;

    private UserUtil() {

    }

    public static UserUtil getInstance() {
        return UserUtilInner.UserUtil;
    }

    private static class UserUtilInner {
        private static UserUtil UserUtil = new UserUtil();
    }

    public static final String KEY_USER = "user";
    static ThreadLocal<String> userThreadLocal = new ThreadLocal<>();

    public  void fillUserInfo(HttpServletRequest request) {
        setUser(request.getAttribute(Constants.CURRENT_USER_ID).toString());
    }

    public  void setUser(String userid) {
        userThreadLocal.set(userid);

        // 把用户信息放到logback
        MDC.put(KEY_USER, userid);
    }

    public  String getUserId() {
        return userThreadLocal.get();
    }

    public  void clearAllUserInfo() {
        userThreadLocal.remove();
        MDC.remove(KEY_USER);
    }
}
